#coding:utf-8

import ConfigParser, os
import Config;
import Global;

### 增加模块这里需要添加 -----------------------------------------------------------
sections=[  'setting','module_recv','module_send',
            'module_terminal','module_variable','module_variable_track',
            'module_video',];


class IniFile:
    def __init__(self, filename):
        
        self.filename = filename
        self.cfg = None
        
        if not os.path.exists(filename):
            f = open(filename, 'w');
            f.close();
            Save();

    def Init(self):
        self.cfg = ConfigParser.ConfigParser()
        try:
            readhandle = open(self.filename, 'r')
            self.cfg.readfp(readhandle)
            readhandle.close()
        except:
            ELog.Trace();

    def Save(self):
        try:
            writehandle = open(self.filename, 'w')
            self.cfg.write(writehandle)
            writehandle.close()
        except:
            ELog.Trace();

    def Get(self, Section, Key, Default = ""):
        try:
            value = self.cfg.get(Section, Key)
        except:
            value = Default
        return value

    def Set(self, Section, Key, Value):            
        try:
            self.cfg.set(Section, Key, Value)
        except:
            self.cfg.add_section(Section)
            self.cfg.set(Section, Key, Value)       

def Save():
    setting=IniFile(Global.env['app_root']+"setting.ini");
    setting.Init();
    for section in sections:
        for key, value in Config.APP_CONFIG[section].items():
            setting.Set(section,key,value);
    setting.Save();
        
        
def Load():
    setting=IniFile(Global.env['app_root']+"setting.ini");
    setting.Init();
    for section in sections:
        for key, value in Config.APP_CONFIG[section].items():
            Config.APP_CONFIG[section][key] = setting.Get(section, key, Config.APP_CONFIG[section][key])    

